#!/usr/bin/env python3
import random

import requests
from datetime import datetime
import os.path
import time

import json

import config

from db_helper import DbHelper
from http_helper import HttpHelper
from param_model import ParamModel

http = HttpHelper()
db = DbHelper()
param = ParamModel()

creator_token = ''


def write_act_comments():
    resp = http.fetch_my_act()
    for record in resp['records']:
        # print('----', record['id'], record['evaluateStatus'], record['clubId'])
        if record['clubId'] == 10727 and record['evaluateStatus'] == 0:
            comment = db.get_random_comment()
            print(f'新建评论 act:{act_id} and comment:{comment.content}')

            param = {
                "activityId": act_id,
                "clubId": None,
                "evaluateType": 1,
                "mainScore": 5,
                "serviceScore": 5,
                "environmentScore": 5,
                "experienceScore": 5,
                "content": comment.content,
                "pics": comment.image_url,
                "evaluateTarget": 0
            }
            http.create_comment(param)
            break


def assign_temp_admin():
    print('开始为丰台活动设置临时管理员')
    http.set_flash_token(creator_token)
    acts = http.fetch_club_activities(config.HY_CLUB_ID)['records']
    for act in acts:
        if act['activityAddress'] == '康城羽毛球馆' and (act['startTime'] == '12:00' or act['startTime'] == '14:00'):
            print('康城下午场活动：', act['id'])
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2990797])
                print('为活动设置临时管理员......', ret)
                # print('add admin result:::::::::', ret)
        elif act['activityAddress'] == '209玉泉营羽毛球馆' or (
                act['activityAddress'] == '康城羽毛球馆' and act['startTime'] == '18:00'):
            admins = http.fetch_temp_admin(act['id'])
            if not isinstance(admins, list):
                # 未设置管理员时此处不会返回列表
                ret = http.add_temp_admin(act_id=act['id'], member_id_list=[2771390, 2675656])
                print('为活动设置临时管理员......', ret)
        time.sleep(3)


def confirm_account():
    # 检查所有账号的token过期情况d
    accounts = db.get_user_accounts()
    for account in accounts:
        print('user:', account.to_dict())
        data = account.to_dict()
        last_update = data['last_update']
        expired = False

        # print("时间差:", datetime.now().timestamp() - last_update.timestamp())
        if last_update is not None and datetime.now().timestamp() - last_update.timestamp() > config.TOKEN_EXP_SECONDS:
            expired = True

        access_token = data['access_token']
        if access_token is None or expired:
            # print('token无效或已过期，重新获取', data['phone'], data['password'])
            access_token = http.login_in(data['phone'], data['password'])
            # print('phone:', data['phone'], access_token)
            db.update_account_account(data['phone'], access_token)
            # 等待10秒再处理下一个账号
            time.sleep(10)
        # player_tokens.append(access_token)
        # if data['member_name'] == '小伙伴':
        #     http.set_flash_token(access_token)
        #     ret = http.join_club(8474)
        #     print('join club result:::::::::', ret)

    # 获取管理账号
    admin = db.get_admin_account()
    if admin is None:
        print('Admin account not found, exit.')
    else:
        data = admin.to_dict()
        access_token = data['access_token']
        if data['last_update'] is None or datetime.now().timestamp() - data[
            'last_update'].timestamp() > config.TOKEN_EXP_SECONDS:
            # token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21QYXJhbWV0ZXIiOiJxd2VyMTIzNCIsInVzZXJJZCI6ODM1MjY1LCJleHAiOjE3NjE1MzkwMzZ9.9f-ucoi9of2_kmZu0i6184eAd2kZ_0a02OPvx7XiKbc'
            access_token = http.login_in(data['phone'], data['password'])
            db.update_account_account(data['phone'], access_token)
            # token = 'token'
        # 为http接口设置管理员token
        global creator_token
        creator_token = access_token
        # http.set_flash_token(access_token)
        # ret = http.user_detail()
        # print('login result:', ret)


# def query_act(act_id, access_token):
#     url = f'https://flash.flashxsport.com/flash/activity/detail?activityId={act_id}&latitude=&longitude='
#     return fetch_flashx(url,)

if __name__ == "__main__":

    # admin = db.get_admin_account()
    # admin_token = admin.access_token
    need_set_temp_admin = False
    confirm_account()

    while True:

        now = datetime.now()
        # 6点设置一次临时管理员和重置各token
        if now.hour == 6 and need_set_temp_admin:
            need_set_temp_admin = False
            # confirm_account()
            assign_temp_admin()

        # 11点重置临时管理员变量
        if now.hour == 23:
            need_set_temp_admin = True
        # if now.hour == 6:
        confirm_account()

        today = now.strftime('%Y-%m-%d')
        acts = db.get_next_act()
        for act in acts:
            # 每个活动创建时同步写一条好评
            write_comment = True
            # 创建活动的参数
            data = param.create_single_act(act.club_id, act.title, today, act.start_hour, act.end_hour,
                                           act.member_count, act.price)
            data['placeDo'] = {
                'city': act.city,
                'region': act.region,
                'placeName': act.place_name,
                'latitude': act.latitude,
                'longitude': act.longitude,
                'address': act.address
            }
            # print('data is:', data)
            # break
            # 调用接口创建活动
            print(
                f'正在创建活动，地点：{act.place_name},人数：{act.member_count},开始时间：{act.start_hour},结束时间：{act.end_hour}')
            http.set_flash_token(creator_token)
            act_id = http.create_act(data)
            group_id = http.get_act_group(act_id)['actGroups'][0]['groupId']
            print(f'活动已创建，id:{act_id}, group id: {group_id}')
            for idx in range(0, act.member_count):
                # 随机等待一个时间后报名参与活动30-90秒
                wait_secs = int(random.random() * 60) + 200
                print('即将开始报名：', wait_secs, act_id, group_id)
                time.sleep(wait_secs)
                # 从数据库读取一个账号
                acc = db.get_apply_account()
                http.set_flash_token(acc.access_token)
                http.join_act(act_id, group_id, act.price)
                print(f'加入活动结束：{idx + 1} / {act.member_count}')
                if random.random() > 0.9:
                    print('稍后生成一条俱乐部好评。')
                    time.sleep(20)
                    write_comment = False
                    write_act_comments()

        print('本轮创建活动结束，5分钟后再次检测任务')
        time.sleep(300)
